class MyGame extends Phaser.Scene {
  preload() {
    this.load.image('tankall', 'images/tankAll.gif');
    this.load.spritesheet('bullet_fire', 'images/bullet_fire.png', { frameWidth: 16, frameHeight: 16 });
    this.load.spritesheet('bullet_ice', 'images/bullet_ice.png', { frameWidth: 16, frameHeight: 16 });
    this.load.spritesheet('bullet_flare', 'images/bullet_flare.png', { frameWidth: 16, frameHeight: 16 });
  }

  create() {
    this.mapData = generateMap(25, 25);
    this.mapLayer = this.add.layer();

    for (let row = 0; row < this.mapData.length; row++) {
      for (let col = 0; col < this.mapData[row].length; col++) {
        const id = this.mapData[row][col];
        if (id === 0) continue;
        const crop = tileCrop[id];
        if (!crop) continue;
        const px = col * TILE_SIZE;
        const py = row * TILE_SIZE;
        const tile = this.add.image(px, py, 'tankall')
          .setOrigin(0, 0)
          .setCrop(crop.x, crop.y, TILE_SIZE, TILE_SIZE);
        this.mapLayer.add(tile);
      }
    }

    for (const type in BULLET_TYPES) {
      const cfg = BULLET_TYPES[type];
      this.anims.create({
        key: cfg.anim,
        frames: this.anims.generateFrameNumbers(cfg.key, { start: 0, end: 3 }),
        frameRate: 10,
        repeat: -1
      });
    }

    this.enemyGroup = this.physics.add.group();
    this.enemyTanks = [];
    for (let i = 0; i < 3; i++) {
      const ex = Phaser.Math.Between(200, 600);
      const ey = Phaser.Math.Between(100, 400);
      const enemy = new EnemyTank(this, ex, ey);
      this.enemyTanks.push(enemy);
      this.enemyGroup.add(enemy.sprite);
    }

    this.tank = new Tank(this, 100, 100);
    this.cursors = this.input.keyboard.createCursorKeys();
    this.bulletManager = new BulletManager(this);
    this.spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

    // ✅ 玩家子弹打中敌人
    this.physics.add.overlap(
      this.bulletManager.group,
      this.enemyGroup,
      this.onBulletHitEnemy,
      (bullet, enemySprite) => bullet.getData('owner') === 'player',
      this
    );

    // ✅ 敌人子弹打中玩家
    this.physics.add.overlap(
      this.bulletManager.group,
      this.tank.sprite,
      this.onBulletHitPlayer,
      (bullet, tankSprite) => {
        const owner = bullet.getData('owner');
        console.log('💥 检测到子弹命中玩家，owner =', owner); // ✅ 调试输出
        return owner === 'enemy';
      },
      this
    );

    this.currentBulletType = 'fire';
    this.input.keyboard.on('keydown-Q', () => {
      this.currentBulletType = 'fire';
      console.log('Switched to 🔥 Fire bullet');
    });
    this.input.keyboard.on('keydown-W', () => {
      this.currentBulletType = 'ice';
      console.log('Switched to ❄️ Ice bullet');
    });
    this.input.keyboard.on('keydown-E', () => {
      this.currentBulletType = 'flare';
      console.log('Switched to 💡 Flare bullet');
    });

    this.explosions = this.add.group({ runChildUpdate: true });
  }

  update(time, delta) {
    this.tank.update(this.cursors, delta / 1000);
    if (Phaser.Input.Keyboard.JustDown(this.spaceKey)) {
      const offset = (TANK_SIZE - 16) / 2;
      this.bulletManager.shoot(this.tank.x + offset, this.tank.y + offset, this.tank.dir, this.currentBulletType, 'player');
    }
    this.bulletManager.update();
    for (const enemy of this.enemyTanks) {
      enemy.update(delta / 1000, this.bulletManager);
    }
    Phaser.Actions.Call(this.explosions.getChildren(), explosion => {
      explosion.update(delta / 1000);
    });
  }

  onBulletHitEnemy(bullet, enemySprite) {
    bullet.setActive(false);
    bullet.setVisible(false);
    bullet.body.stop();
    new Explosion(this, enemySprite.x, enemySprite.y);
    enemySprite.destroy();
    console.log('💥 敌人被击中并炸毁！');
  }

  onBulletHitPlayer(bullet, tankSprite) {
    bullet.setActive(false).setVisible(false).body.stop();
    new Explosion(this, tankSprite.x, tankSprite.y);
    tankSprite.setActive(false);  // ✅ 不直接 destroy
    tankSprite.setVisible(false);
    console.log('💥 玩家被击中！游戏结束或处理扣血逻辑');
  }
}

new Phaser.Game({
  type: Phaser.AUTO,
  width: 50 * TILE_SIZE,
  height: 50 * TILE_SIZE,
  backgroundColor: '#000',
  scene: MyGame,
  physics: {
    default: 'arcade',
    arcade: {
      debug: false
    }
  }
});
